Python模組入門
在 Python 中,一個 模組 是以 .py的檔案,作為可重用程式碼元件(函數、類別、變數)的容器。模組是大型程式架構的核心,讓開發者能透過邏輯上分離定義來管理複雜性並提升程式碼維護性。此過程類似於數學概念如何被劃分為專門領域(例如,$f(x)$ 在特定定義域 $D$ 內定義)。
1. 模組的功能
模組解決開發中的三個關鍵需求:
- 促進 程式碼重用在多個專案中重用,無需重新撰寫定義。
- 透過將大型程式分割成可管理且相關的檔案,確保清晰與條理。
- 防止 命名衝突透過為函數和變數定義獨立的命名空間來避免。
概念範例:
想像有一個名為
utility.py 的檔案,內含用於計算數學結果的函數。整個檔案即為模組,而這些函數便是其可存取的內容。
2. 匯入方式
Python 的 import語句使外部定義對您目前的腳本可用。所選方法決定了您如何存取元件,以及當前程式的命名空間會受到何種影響。
- 標準匯入:
import module_name。需要使用module_name.function()來存取內容。 - 選擇性匯入:
from module import function。允許直接使用function(),無需模組前綴。 - 使用別名匯入:
import module as alias。提供較短、專案特定的暱稱以方便使用(例如,import numpy as np)。
標準函式庫重點
Python 包含廣泛的 標準函式庫 內建模組(如 'os'、'sys'、'random'、'math')。學習如何有效利用這些可重用的模組,對於高效開發至關重要,並能節省大量時間。
Question 1
If you use
import math, how must you call the sqrt function to calculate $\sqrt{25}$?Question 2
Which benefit of using modules addresses the issue of having multiple functions named
process_data in a large application?Question 3
What happens to a module file the second time you attempt to
import it in the same running program?